import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import CustomImage from './CustomImage'
import { ImageBackground } from 'react-native'
import { defaultPortraitGray } from '../../utils/ConfigUtil'

export default class DefaultImage extends PureComponent {
  constructor (props) {
    super(props)
    this.state = {
      showDefault: true,
      imgOpacity: 0,
      source: props.source
    }
    const styleArr = [].concat(props.style)
    this.style = styleArr.reduce((allStyle, currentValue) => ({
      ...allStyle, ...currentValue
    }), {})
  }

  UNSAFE_componentWillReceiveProps (nextProps) {
    const { source: { uri: thisUri } = {} } = this.props
    const { source: { uri: nextUri } = {} } = nextProps
    if (thisUri !== nextUri) {
      this.setState({
        source: nextProps.source
      })
    }
  }

  render () {
    const { defaultSource = defaultPortraitGray } = this.props
    const { source } = this.state
    const { width, height, borderRadius } = this.style
    return (
      <ImageBackground source={defaultSource} style={this.style}>
        <CustomImage
          style={[{ width, height, borderRadius }]}
          source={source}
          resizeMode='cover'
          onLoad={this._onLoad}
          onError={this._onError}
        />
      </ImageBackground>
    )
  }

  _onLoad = () => {
  }

  _onError = () => {
    const { errorSource } = this.props
    if (errorSource) {
      this.setState({
        source: errorSource,
        imgOpacity: 1
      })
    }
  }
}
DefaultImage.propTypes = {
  style: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
  source: PropTypes.oneOfType([PropTypes.object, PropTypes.number]),
  errorSource: PropTypes.oneOfType([PropTypes.object, PropTypes.number]),
  refImg: PropTypes.func,
  defaultSource: PropTypes.number,
  onError: PropTypes.func
}
